package ks.client.gui.login.listeners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import ks.client.controllers.framework.ConnectController;
import ks.client.controllers.framework.DisconnectController;
import ks.client.gui.login.LoginGUI;
import ks.client.lobby.Lobby;

import ks.client.UserContext;


/**
 * @author Christopher Page
 */
public class ConnectListener implements ActionListener {
	
	Lobby lobby;
	UserContext context;
	
	public ConnectListener (Lobby lobby) {
		this.lobby = lobby;
		this.context = lobby.getUserContext();
	}

	/**
	 * Constructs and sends the message on the button click.
	 * 
	 */
	public void actionPerformed (ActionEvent e) {
		LoginGUI gui = lobby.getLoginGUI();
		
		if (gui != null) {
			String hostname = gui.getHostname();
			int port = gui.getPort();
			String username = gui.getUsername();
			char[] chars = gui.getPassword();
			boolean selfRegister = gui.getSelfRegister();
			gui.setFieldsEnabled(false);
		
			String password = new String("");
		
			for (char c : chars) {
				password = password + c;
			}
			for (int i = 0; i < chars.length; i++) {
				chars[i] = '\0';   // protect.
			}
			
			context.setHost(hostname);
			context.setPort(port);
			context.setUser(username);
			context.setPassword(password);
			context.setSelfRegister(selfRegister);
		
			if (new ConnectController(lobby).process(context))
				lobby.connected(true);
			else {
				if (new DisconnectController(lobby).process(context))
					lobby.connected(false);
				else
					gui.setFieldsEnabled(true);
			}
		}
	}
}
